<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="修改"
    width="80%"
    :before-close="handleClose"
    class="task-form-dialog"
    :close-on-click-modal="false"
  >
    <div class="severe-damage-form">
      <div class="form-header">
        <h2 class="form-title">严重损坏房屋巡查</h2>
      </div>

      <el-form
        ref="severeForm"
        :model="formData"
        :rules="rules"
        label-width="220px"
        label-position="left"
        class="form-content"
        :validate-on-rule-change="false"
      >
        <!-- 基本情况 -->
        <div class="section inspection-item">
          <h3 class="section-title">基本情况</h3>

          <!-- 地址行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="formData.address" placeholder="请输入地址">
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="存在问题" prop="addressStatus">
                <el-select
                  v-model="formData.addressStatus"
                  placeholder="选择存在问题"
                >
                  <el-option label="选择存在问题" value=""></el-option>
                  <el-option label="存在问题" value="exists"></el-option>
                  <el-option label="无问题" value="none"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>

          <!-- 层数行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地上层数（层）" prop="aboveGroundFloors">
                <el-input-number
                  v-model="formData.aboveGroundFloors"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                />
                <!-- <el-input v-model="formData.aboveGroundFloors"></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地下层数（层）" prop="undergroundFloors">
                <el-input-number
                  v-model="formData.undergroundFloors"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 建筑面积和高度行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="建筑面积（平方米）" prop="buildingArea">
                <el-input-number
                  v-model="formData.buildingArea"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建筑高度（米）" prop="buildingHeight">
                <el-input-number
                  v-model="formData.buildingHeight"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 建筑期间和房屋套数行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="建筑期间" prop="buildingPeriod">
                <el-date-picker
                  v-model="formData.buildingPeriod"
                  type="year"
                  placeholder="2025"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房屋套数（套）" prop="houseCount">
                <el-input-number
                  v-model="formData.houseCount"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 房屋用途和保护建筑性质行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房屋用途" prop="houseUsage">
                <!-- <el-radio-group v-model="formData.houseUsage">
                  <el-radio
                    v-for="item in dictData.houseUsageDict"
                    :key="item.id"
                    :label="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group> -->
                <el-input v-model="formData.houseUsage"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择保护建筑性质" prop="protectionNature">
                <el-radio-group v-model="formData.protectionNature">
                  <el-radio
                    v-for="item in dictData.protectionNatureDict"
                    :key="item.id"
                    :label="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 保护建筑类型行 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="保护建筑类型" prop="protectionType">
                <el-radio-group v-model="formData.protectionType">
                  <el-radio
                    v-for="item in dictData.protectionTypeDict"
                    :key="item.id"
                    :label="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 结构类型行 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="结构类型" prop="structureType">
                <el-radio-group v-model="formData.structureType">
                  <el-radio
                    v-for="item in dictData.structureTypeDict"
                    :key="item.id"
                    :label="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 楼板形式行 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="楼（房间）板形式" prop="floorForm">
                <el-radio-group v-model="formData.floorForm">
                  <el-radio
                    v-for="item in dictData.floorFormDict"
                    :key="item.id"
                    :label="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 装修部分 taskList-->
        <div v-for="(item, index) in taskList" :key="index">
          <div class="section structure-section">
            <h3 class="section-title">{{ item.name }}</h3>
            <div v-for="(it, idx) in item.children" :key="idx">
              <el-row :gutter="20" v-if="it.paramType == 1">
                <el-col :span="8">
                  <el-form-item :label="it.name">
                    <el-radio-group v-model="it.nameValue">
                      <el-radio label="1">是</el-radio>
                      <el-radio label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <div v-for="(its, idxs) in it.children" :key="idxs">
                <el-row :gutter="20" v-if="its.paramType == 2">
                  <el-col :span="12">
                    <el-form-item label-width="0">
                      <el-checkbox
                        :true-label="'1'"
                        :false-label="'0'"
                        v-model="its.nameValue"
                        >{{ its.name }}</el-checkbox
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- 城市体检附件 -->
                <el-row v-if="its.paramType == 4">
                  <el-col :span="24">
                    <el-form-item
                      :label="its.name"
                      prop="cityInspectionAttachments"
                    >
                      <el-upload
                        class="upload-demo"
                        action="http://125.39.77.18:9021/mall-admin/fileUpload/upload"
                        :file-list="its.nameValue"
                        list-type="picture"
												 :on-success="(response, file, fileList) => 
												 handleUploadSuccess(response, file, fileList,its.id)"
												 :on-remove="(response, file, fileList) => 
												 handleFileRemove(file, fileList,its.id)"
												 :limit='1'
                      >
                        <el-button size="small" type="primary"
                          >点击上传</el-button
                        >
                        <div slot="tip" class="el-upload__tip">
                          只能上传jpg/png文件，且不超过500kb
                        </div>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="its.paramType == 3">
                  <el-col :span="12">
                    <el-form-item :label="its.name" prop="address">
                      <el-input v-model="its.nameValue" type=""> </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button v-if="types == 1" type="primary" @click="handleSubmit">
          提交
        </el-button>
        <el-button v-if="types == 2" type="primary" @click="handleClose">
          关闭
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  surveyTaskChecksByTaskId,
  updateSurveyTaskLedgerCheck,
} from "@/api/safe/fangwuanquankancha/xuncharenwuliebiao";
import managementFileUpload from "@/components/managementFileUpload.vue";
export default {
  name: "SevereDamageForm",
  components: {
    managementFileUpload,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    taskId: {
      type: Number,
      default: false,
    },
    types: {
      type: Number,
      default: false,
    },
    currentdata: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      formData: {
        address: "",
        aboveGroundFloors: "",
        buildingArea: "",
        houseUsage: "",
        buildingPeriod: "",
        buildingHeight: "",
        houseCount: "",
      },
      rules: {},
      dictData: {},
      checked: "",
      taskList: [],
      uploadDialogVisible: false,
      fileList: [],
      // 字典数据
      dictData: {
        // 房屋用途
        houseUsageDict: [
          { id: "residential", name: "住宅" },
          { id: "non-residential", name: "非住宅" },
        ],
        // 保护性质
        protectionNatureDict: [
          { id: "yes", name: "是" },
          { id: "no", name: "否" },
        ],
        // 保护类型
        protectionTypeDict: [
          { id: "national", name: "全国重点文物保护单位" },
          { id: "municipal", name: "市级文物保护单位" },
          { id: "district", name: "区级文物保护单位" },
          { id: "historical", name: "历史建筑" },
          { id: "unregistered", name: "未登记等级" },
          { id: "characteristic", name: "历史风貌建筑（特殊）" },
          { id: "general", name: "历史风貌建筑（重点）" },
          { id: "disaster", name: "历史风貌建筑（一般）" },
        ],
        // 结构类型
        structureTypeDict: [
          { id: "brick", name: "砖混结构" },
          { id: "steel", name: "钢筋混凝土上结构" },
          { id: "steel-wood", name: "钢木结构" },
          { id: "brick-wood", name: "砖木结构" },
          { id: "other", name: "其他" },
        ],
        // 楼层形式
        floorFormDict: [
          { id: "precast", name: "预制" },
          { id: "cast-in-place", name: "现浇空心楼" },
          { id: "wood", name: "木楼（房间）板" },
          { id: "no-floor", name: "无楼板" },
          { id: "other", name: "其他" },
        ],
      },
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  created() {
    surveyTaskChecksByTaskId(this.taskId).then((res) => {
      this.taskList = res.data.list;
			
			this.taskList.forEach((item,index)=>{
				item.children.forEach((it,idx)=>{
					it.children.forEach((its,idxs)=>{
						if(its.paramType == 4){
							if(its.nameValue){
								its.nameValue = JSON.parse(its.nameValue)
							}else{
								its.nameValue = []
							}
						}
					})
				})
			})
			console.log(this.taskList);
    });
  },
  mounted() {
    const {
      address,
      livingway,
      buildyear,
      floorcount,
      buildingarea,
      hight,
      roomcount,
    } = { ...this.currentdata };
    this.formData.address = address;
    this.formData.aboveGroundFloors = floorcount;
    this.formData.buildingArea = buildingarea;
    this.formData.houseUsage = livingway;
    this.formData.buildingPeriod = buildyear;
    this.formData.buildingHeight = hight;
    this.formData.houseCount = roomcount;
  },
  methods: {
    handleSubmit() {
			this.taskList.forEach((item,index)=>{
				item.children.forEach((it,idx)=>{
					it.children.forEach((its,idxs)=>{
						if(its.paramType == 4){
							if(its.nameValue){
								its.nameValue = JSON.stringify(its.nameValue)
							}
						}
					})
				})
			})
			
      updateSurveyTaskLedgerCheck(this.taskList).then((res) => {});
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.$emit("close");
    },
    resetForm() {
      if (this.$refs.formRef && this.$refs.formRef.resetForm) {
        this.$refs.formRef.resetForm();
        this.$message.success("表单已重置");
      }
    },

    // 扫描件上传
    handleUploadScan() {
      this.uploadDialogVisible = true;
    },
    uploadClose() {
      this.uploadDialogVisible = false;
    },
		handleUploadSuccess(response, file, fileList,id){
			if (response.code == 200) {
				this.$message.success('文件上传成功');
				console.log(response, file, fileList,id)
				this.taskList.forEach((item,index)=>{
					item.children.forEach((it,idx)=>{
						it.children.forEach((its,idxs)=>{
							if(its.id == id){
								its.nameValue.push({
									name:file.name,
									url:response.data.url
								})
							}
						})
					})
				})
			} else {
				this.$message.error('文件上传失败');
					
			}
		},
		handleFileRemove(file, fileList,id){
			
			this.taskList.forEach((item,index)=>{
				item.children.forEach((it,idx)=>{
					it.children.forEach((its,idxs)=>{
						if(its.id == id){
							its.nameValue = []
						}
					})
				})
			})
		}
  },
};
</script>

<style scoped>
.severe-damage-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

/* el-form-item 样式调整 */
::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #409eff;
}

.form-title {
  margin: 0;
  color: #409eff;
  font-size: 24px;
  font-weight: bold;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  padding: 10px;
  background: #f5f7fa;
  border-left: 4px solid #409eff;
}

.structure-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 10px;
  background: #fafafa;
}

/* Element UI 组件样式调整 */
::v-deep .el-input-number {
  width: 100%;
}

::v-deep .el-date-picker {
  width: 100%;
}

::v-deep .el-textarea .el-textarea__inner {
  resize: vertical;
}

::v-deep .el-radio {
  margin-right: 15px;
}

::v-deep .el-radio__label {
  font-size: 14px;
}

.inspection-item {
  margin-bottom: 10px;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }
}
.items .el-form-item__content {
  margin-left: 0px !important;
}
</style>
